import * as VueRouter from 'vue-router'
import 'nprogress/nprogress.css'
import routes from './common'
import _ from 'lodash'
import store from '@jsjn/micro-core-store'
import { routeMode } from '@jsjn/micro-core-micro-main/routeMode'
import getFrontEndRoutes from './frontEnd'
import backEnd from './backEnd'
import packInfo from '@ROOT/package.json'

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes
})

// 前置
router.beforeEach(async (to, from) => {
    store.commit('currentStatus/setRouteLoading', true)

    /**
     * 后端控制路由下，有可能存在微应用路由（业务路由）未注册的情况
     * 即 remoteRegisteredRoutes 有效路由为空
     */
    if (
        routeMode === 'backEnd' &&
        store.state.appFuncTree.remoteRegisteredRoutes.filter(
            (route) => route.path.startsWith(`/${packInfo.name}`) && !route.path.endsWith(':page*')
        ).length === 0
    ) {
        return true
    }

    /**
     * 这里忽略了微应用的静态路由模块为空时的情况，导致静态路由情况下，注册列表始终为空
     * 这里判断如果静态路由配置（modules）为空时，放行（页面 404）
     */
    if (routeMode === 'frontEnd' && getFrontEndRoutes().length === 0) {
        return true
    }

    /**
     * 由于微应用的路由模式都要跟随基座应用的模式
     * 故：路由的注册要放到运行阶段
     * 动态的判断 microApp.routeMode 进行路由的动态添加
     */
    if (routeMode && store.state.appFuncTree.registeredRoutes.length === 0) {
        // 静态路由
        if (routeMode === 'frontEnd') {
            store.commit('appFuncTree/setRegisteredRoutes', getFrontEndRoutes())
            getFrontEndRoutes().forEach((route: any) => {
                router.addRoute(route)
            })
        }

        // 动态路由，基座应用为异步加载，微应用是同步
        if (routeMode === 'backEnd') {
            backEnd(router)
        }

        // 添加完路由后，重定向到 to
        return {
            ...to,
            replace: true
        }
    }

    return true
})

// 后置
router.afterEach(async (to, from) => {
    store.commit('currentStatus/setRouteLoading', false)
})

export default router
